package ele_handler

import (
	"fmt"
	"go-yuque/logger"
	"golang.org/x/net/html"
	"path/filepath"
	"strings"
)

func init() {
	registerInitFunc(
		func() YuqueElementHandler {
			h := &cardBoardHandlerStruct{}
			h.elements = []string{"card"}
			h.attributes = map[string]string{"name": "board"}
			return h
		})
}

type cardBoardHandlerStruct struct {
	BaseHandler
	imageBase
}

func (cb *cardBoardHandlerStruct) doHandle() (err error) {

	err = parseCardJson(cb.node, cb)
	if err != nil {
		logger.Errorf("[cardBoard]解析异常")
		sb := strings.Builder{}
		err = html.Render(&sb, cb.node)
		if err != nil {
			cb.WriteTextContext(sb.String())
		}
		return
	}

	// 直接放图片
	if len(cb.Src) <= 0 {
		logger.Errorf("[cardBoard]src为空")
		return fmt.Errorf("[cardBoard]src为空")
	}
	imageName := filepath.Base(cb.Src)
	err = getImage(cb.imageBase, imageName, cb.downloadTocPath, cb)

	return
}
